package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import base.DbConnect;
import base.Session;
import base.Sql;

public class UserAccess {
	// 验证数据
	public static String getPassword(String username) {
		Connection conn = DbConnect.getConnect();
		Statement stmt = null;
		ResultSet rs = null;
		String password = null;
		try {
			stmt = conn.createStatement();
			String sql;
//			sql = "SELECT t_password FROM teacher where t_id = '" + username + "'";
			sql = Sql.createSql("SELECT", Session.idStatus, "t_id = '" + username + "'");
			rs = stmt.executeQuery(sql);
			if (rs.next()) {
				password = rs.getString("t_password");
			}
		} catch (SQLException se) {
			// 处理 JDBC 错误
			se.printStackTrace();
		} catch (Exception e) {
			// 处理 Class.forName 错误
			e.printStackTrace();
		} finally {
			try {
				stmt.close();
				conn.close();
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return password;
	}

	public static int changePassword(String username,String password) {
		// 1.定义声明对象
		Connection conn = DbConnect.getConnect();
		PreparedStatement  stmt = null;
		int res = 0;
		try {
			// sql语句赋值 赋值为待执行的sql语句
			String sql = "update user set password = ? where username = ?";
			// 从数据库的连接中获取创建声明对象
			stmt = conn.prepareStatement(sql);
			stmt.setString(1, password);
			stmt.setString(2, username);
			res = stmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				stmt.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return res;
	}
	public static int addUser(String username,String password) {
		Connection conn = DbConnect.getConnect();		
		PreparedStatement stmt = null;
		int res = -1;
		String sql = "insert into user values (?,?)";
		try {
			stmt = (PreparedStatement) conn.prepareStatement(sql);
			stmt.setString(1, username);
			stmt.setString(2, password);
			res = stmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return res;
	}
}
